﻿using System;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;

namespace mvcForum.Core {

	public static class ICustomPropertyHolderExtensions {

		private static void LoadProperties(ICustomPropertyHolder holder) {
			if (holder.CustomData == null) {
				if (!String.IsNullOrWhiteSpace(holder.CustomProperties)) {
					holder.CustomData = XDocument.Parse(holder.CustomProperties);
				}
				else {
					holder.CustomData = new XDocument(new XElement("CustomProperties"));
				}
			}
		}

		public static Dictionary<String,String> GetCustomProperties(this ICustomPropertyHolder holder) {
			LoadProperties(holder);
			return holder.CustomData.Root.Elements("CustomProperty").ToDictionary(e => e.Attribute("Name").Value, e => e.Value, StringComparer.OrdinalIgnoreCase);
		}

		public static String GetCustomProperty(this ICustomPropertyHolder holder, String key) {
			LoadProperties(holder);
			XElement property = holder.CustomData.Root.Elements("CustomProperty").Where(p => p.Attribute("Name") != null && p.Attribute("Name").Value == key).FirstOrDefault();
			if (property != null) {
				return property.Value;
			}
			return String.Empty;
		}

		public static void SetCustomProperty(this ICustomPropertyHolder holder, String key, String value) {
			LoadProperties(holder);
			XElement property = holder.CustomData.Root.Elements("CustomProperty").Where(p => p.Attribute("Name") != null && p.Attribute("Name").Value == key).FirstOrDefault();
			if (property == null) {
				holder.CustomData.Root.Add(new XElement("CustomProperty", new XAttribute("Name", key), new XCData(value)));
			}
			else {
				property.Value = value;
			}

			holder.CustomProperties = holder.CustomData.ToString();
		}
	}
}